<template>
  <div class="system-toolbar">
    <div class="toolbar-container">
      <div class="toolbar-container-left">
        <div class="toolbar-logo">
          <router-link :to="{ name: 'userMain' }"
            ><img src="../assets/images/系统logo4.png" alt="" class="logo-image"
          /></router-link>
        </div>
      </div>
      <div class="toolbar-container-middle">
        <div class="middle-box">
          <el-button
            type="text"
            size="big"
            class="toolBar-button"
            @click="goAdvancedSearch"
            >高级搜索</el-button
          >
          <div class="search-input" style="width: 480px">
            <!-- 回车检索，监听回车原生事件 -->
            <el-input
              placeholder="请输入需要检索的内容"
              size="medium"
              clearable
              v-model="searchText"
              @keyup.enter.native="searchArticles(searchText)"
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
              <el-button slot="append" @click="searchArticles(searchText)"
                >检索</el-button
              ></el-input
            >
          </div>
          <div class="write-blog" style="width: max-content">
            <el-button type="text" size="big" @click="goWriteBlog" class="toolBar-button"
              >发布文章</el-button
            >
          </div>
          <div
            class="audit-blog"
            style="width: max-content"
            v-if="isAuditor || isAmin"
          >
            <el-button type="text" size="big" @click="auditBlog" class="toolBar-button"
              >审核文章</el-button
            >
          </div>
          <div class="system-manage" style="width: max-content" v-if="isAmin">
            <el-button type="text" size="big" @click="systemManagement" class="toolBar-button"
              >系统管理</el-button
            >
          </div>
          <div class="wenXinChat" style="width: max-content">
            <el-button type="text" size="big" @click="goWenXinChat" class="toolBar-button"
              >AI助手</el-button
            >
          </div>
        </div>
      </div>
      <div class="toolbar-container-right">
        <!-- 通知等信息,悬浮的下拉选择框 -->
        <div class="my-message">
          <el-badge
            :value="totalMessageNum"
            class="item"
            :max="99"
            :hidden="totalMessageNum <= 0"
          >
            <!-- 下拉选择框的触发组件 -->
            <el-dropdown @command="handleMessageCommand">
              <div class="icon-container">
                <i class="el-icon-message-solid my-message-icon"></i>
              </div>
              <!-- 下拉选择框的下拉菜单 -->
              <el-dropdown-menu slot="dropdown">
                <!-- 每一项数据和标签数据 -->
                <el-dropdown-item icon="el-icon-thumb" command="likeMessage"
                  >收到的赞
                  <el-badge
                    class="item"
                    :value="dropdownConfig.likeMessage"
                    :max="99"
                    :hidden="dropdownConfig.likeMessage <= 0"
                /></el-dropdown-item>
                <el-dropdown-item
                  icon="el-icon-chat-line-square"
                  command="commentMessage"
                  >收到的评论
                  <el-badge
                    class="item"
                    :value="dropdownConfig.commentMessage"
                    :max="99"
                    :hidden="dropdownConfig.commentMessage <= 0"
                /></el-dropdown-item>
                <el-dropdown-item
                  icon="el-icon-star-off"
                  command="collectionMessage"
                  >收到的收藏
                  <el-badge
                    class="item"
                    :value="dropdownConfig.collectionMessage"
                    :max="99"
                    :hidden="dropdownConfig.collectionMessage <= 0"
                /></el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-badge>
        </div>
        <!-- 设置:系统主题和基本设置 -->
        <div class="drawer-setting-container">
          <el-button
            type="text"
            size="big"
            class="setting-button"
            @click="drawerSettingVisible = true"
            ><i class="el-icon-s-tools"></i
          ></el-button>
          <!-- 设置append-to-body让抽屉作用在body元素上是最高层 -->
          <el-drawer
            :visible.sync="drawerSettingVisible"
            size="20%"
            custom-class="drawer-setting"
            :append-to-body="true"
            :close-on-press-escape="false"
          >
            <div class="drawer-title" slot="title">
              <p class="title-text">设置</p>
            </div>
            <div class="drawer-content">
              <div class="theme-text">
                <p class="setting-item-title">主题</p>
                <div class="message">
                  <p class="setting-item-text">
                    自定义你的系统主题是明亮还是黑暗的主题，或者跟随系统
                  </p>
                </div>
              </div>
              <div class="theme-control-container">
                <el-radio-group v-model="selectTheme" style="width: 100%">
                  <div class="theme-item-container">
                    <el-button
                      type="text"
                      icon="el-icon-sunny"
                      class="theme-icon"
                      @click="selectTheme = 'light'"
                    ></el-button>
                    <el-radio label="light"> 浅白主题</el-radio>
                  </div>
                  <div class="theme-item-container">
                    <el-button
                      type="text"
                      icon="el-icon-moon"
                      class="theme-icon"
                      @click="selectTheme = 'dark'"
                    ></el-button>
                    <el-radio label="dark">暗色主题</el-radio>
                  </div>
                  <div class="theme-item-container">
                    <el-button
                      type="text"
                      icon="el-icon-s-platform"
                      class="theme-icon"
                      @click="selectTheme = 'OS'"
                    ></el-button>
                    <el-radio label="OS">跟随系统</el-radio>
                  </div>
                </el-radio-group>
              </div>
            </div>
          </el-drawer>
        </div>
        <!-- 展示用户头像和下拉标志，点击头像直接进入个人中心，悬浮展示
        个人中心，个人资料，修改密码和退出登录 -->
        <div class="toolBar-personal-info">
          <el-dropdown @command="handlePersonalCommand">
            <div class="toolBar-avatar-image-container">
              <!-- 头像加载的失败回调函数 -->
              <el-avatar
                :size="40"
                :src="partUserInfo.avatarUrl"
                fit="cover"
                shape="square"
                @error="handleAvatarError"
                >User</el-avatar
              >
              <i class="el-icon-arrow-down el-icon--right"></i>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                icon="el-icon-user-solid"
                command="personalCenter"
                >个人中心</el-dropdown-item
              >
              <el-dropdown-item
                icon="el-icon-s-custom"
                command="accountInformation"
                >个人资料</el-dropdown-item
              >
              <el-dropdown-item icon="el-icon-s-tools" command="changePassWord"
                >修改密码</el-dropdown-item
              >
              <el-dropdown-item icon="el-icon-switch-button" command="logout"
                >退出登录</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
// 导入主题工具文件
import useTheme from "@/utils/useTheme";

@Component({
  name: "ToolBar",
})
export default class ToolBar extends Vue {
  mounted() {
    // 接收原页面传递的检索的文本,需要判断是否为空或者通过vuex传参
    // let text = this.$route.query;
    // console.log(text);
  }
  @Prop({ default: false }) isAmin!: boolean;
  @Prop({ default: false }) isAuditor!: boolean;
  searchText: string = "";
  // 用户的部分信息
  partUserInfo: any = {
    userName: this.$store.state.userName,
    avatarUrl: this.$store.state.avatarUrl,
  };

  // 控制设置显示
  drawerSettingVisible: boolean = false;
  // 所选主题
  // 初始主题通过工具文件获取,设置跟随系统
  theme: any = useTheme();
  selectTheme: string = this.theme.theme;
  // 所有信息通知的总数
  totalMessageNum: number = 0;
  // 下拉菜单的配置项,点赞数，评论数，收藏数，审核数
  dropdownConfig: {
    likeMessage: number;
    commentMessage: number;
    collectionMessage: number;
  } = {
    likeMessage: 0,
    commentMessage: 0,
    collectionMessage: 0,
  };
  // 监听数据的变化，变化时更新总的信息数
  @Watch("dropdownConfig", { deep: true, immediate: true })
  onDropdownConfigChange(val: any, oldVal: any) {
    this.totalMessageNum =
      val.likeMessage + val.commentMessage + val.collectionMessage;
  }

  /**
   * 判断当前页面是否已跳转
   * @param link 目标的路由地址
   * @param words 提示信息
   */
  notifyInfo(link: string, words: string): Boolean {
    // console.log(this.$route);
    if (this.$route.path == link) {
      this.$notify({
        title: "提示",
        message: "您当前已经在" + words + "页面",
        type: "warning",
        offset: 50,
        duration: 3000,
      });
      return false;
    }
    return true;
  }
  // 点击高级搜索进行页面跳转
  goAdvancedSearch(): void {
    if (this.notifyInfo("/advancedSearch", "高级搜索")) {
      this.$router.push({ name: "advancedSearch" });
    }
  }
  // 点击发布文章跳转到文章编写页面
  goWriteBlog(): void {
    if (this.notifyInfo("/writeBlog", "文章编写")) {
      this.$router.push({ name: "writeBlog" });
    }
  }
  auditBlog(): void {
    if (this.notifyInfo("/audit", "审核文章")) {
      this.$router.push({ name: "audit" });
    }
  }
  systemManagement(): void {
    if (this.notifyInfo("/admin", "系统管理")) {
      this.$router.push({ name: "admin" });
    }
  }
  goWenXinChat(): void {
    if (this.notifyInfo("/AIView", "AI助手")) {
      this.$router.push({ name: "AIView" });
    }
  }
  // TODO:智能检索推荐
  searchArticles(searchText: string): void {
    // 首先去除字符串首尾的空格，同时避免全是空格
    let trimText = searchText.trim();
    // 非空才进行检索，否则给出提示
    if (trimText !== "" && trimText !== null) {
      // 当前页不在普通检索界面，在新的标签页打开检索界面，在检索界面直接传递参数
      if (this.$route.path !== "/generalSearch") {
        // 打开新的页面后需要将原页面的输入框数据传给新页面
        const route = this.$router.resolve({
          path: "/generalSearch",
          query: { searchText: trimText },
        });
        // 打开新的标签页
        window.open(route.href, "_blank");
      } else {
        // 还是在当前标签页进行路由，这样可以进行鼠标前进和后退，不能按照数据清空的方式
        this.$router.push({
          name: "generalSearch",
          query: { searchText: trimText },
        });
      }
    } else {
      // 空间检索
      this.$notify({
        title: "提示",
        message: "请先输入需要检索的内容",
        type: "warning",
        offset: 50,
        duration: 3000,
        position: "top-left",
      });
    }
  }
  // 头像加载失败的提示信息
  handleAvatarError(): void {
    this.$message({
      message: "头像加载失败,请检查网络或重新刷新",
      showClose: true,
      type: "error",
    });
  }
  // 跳转到个人中心的不同控制面板
  handleMessageCommand(command: string | Number): void {
    this.$message({
      message: "点击了" + command,
      showClose: true,
      type: "success",
    });
    // 对应个人中心中的内容，可以将command改为对相应的标记
    if (command === "likeMessage") {
      // 发送点赞清零通知
    } else if (command === "commentMessage") {
      // 发送评论清零通知
    } else if (command === "collectionMessage") {
      // 发送收藏清零通知
    }
    // this.$router.push({ name: "userMain" });
  }
  // 个人头像的下拉菜单点击事件
  handlePersonalCommand(command: string | Number): void {
    if (
      command === "personalCenter" &&
      this.notifyInfo("/personalCenter/all-articles", "个人中心")
    ) {
      // 跳转到个人中心
      this.$router.push({ name: "personalCenter" });
    } else if (
      command === "accountInformation" &&
      this.notifyInfo("/accountInformation/personal-data", "个人资料")
    ) {
      // 跳转到个人资料
      this.$router.push({ name: "accountInformation" });
    } else if (
      command === "changePassWord" &&
      this.notifyInfo(
        "/accountInformation/account-setting/change-password",
        "修改密码"
      )
    ) {
      // 跳转到修改密码,直接传组件名就行
      this.$router.push({ name: "changePassWord" });
    } else if (command === "logout") {
      this.logout();
    }
  }
  // 退出登录函数，退出登录需要清空本地缓存
  logout(): void {
    // 退出登录的提示操作
    this.$confirm("是否确定退出登录？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        // 清空本地缓存
        localStorage.clear();
        // !TODO:将缓存中的用户信息清空
        sessionStorage.removeItem("store");
        // 跳转到登录界面
        this.$router.replace({ path: "/login" });
      })
      .catch(() => {
        this.$message({
          type: "info",
          message: "已取消退出登录",
        });
      });
  }
}
</script>
<!-- 写两个style进行设置，设置抽屉的样式（在body元素上） -->
<style lang="scss">
@import "@/assets/styles/themes.scss";
//通过custom-class设置抽屉的样式
.drawer-setting {
  // 选中组件的原生内容修改样式
  @include useTheme {
    background-color: getVar("bgColor");
  }
  .drawer-title {
    .title-text {
      font-size: 20px;
      font-weight: 700;
      color: gray;
      text-align: left;
    }
  }

  .drawer-content {
    padding: 20px;

    .theme-text {
      margin-bottom: 20px;

      .setting-item-title {
        font-size: 16px;
        font-weight: 600;
        color: gray;
        text-align: left;
      }

      .message {
        margin-top: 10px;

        .setting-item-text {
          font-size: 14px;
          color: gray;
          text-align: left;
        }
      }
    }

    .theme-control-container {
      margin-top: 10px;

      .theme-item-container {
        display: flex;
        justify-content: left;
        align-items: center;
        margin-bottom: 10px;

        .theme-icon {
          @include useTheme {
            color: getVar("iconColor");
          }
          font-size: 28px;
          margin-right: 10px;
          &:hover {
            @include useTheme {
              color: getVar("iconActiveColor");
            }
          }
        }
      }
    }
  }
}
</style>

<style lang="scss" scoped>
@import "@/assets/styles/themes.scss";
$icon-font-size: 22px;
.system-toolbar {
  width: 100%;
  height: 50px;
  min-height: 50px;
  box-shadow: 0px 5px 5px 0px rgba(0, 0, 0, 0.1);

  // 元素居中
  // 可变样式写在其中
  @include useTheme {
    background-color: getVar("divColor");
    color: getVar("textColor");
  }

  .toolbar-container {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-between;
    padding: 0px 15px;
    box-sizing: border-box;

    .toolbar-container-left {
      width: 250px;
      min-width: 250px;
      height: 100%;
      display: flex;
      justify-content: left;
      align-items: center;

      .toolbar-logo {
        .logo-image {
          width: auto;
          height: 44px;
        }
      }
    }

    .toolbar-container-middle {
      width: 830px;
      min-width: 830px;
      height: 100%;
      // border: 1px solid #2958c7;
      .middle-box {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .toolBar-button {
          @include useTheme {
            color: getVar("textColor");
          }
        }
      }
    }

    .toolbar-container-right {
      width: 250px;
      min-width: 250px;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      .my-message {
        margin-right: 28px;
        .my-message-icon {
          @include useTheme {
            color: getVar("iconColor");
          }
          &:hover {
            @include useTheme {
              color: getVar("iconActiveColor");
            }
          }
          font-size: $icon-font-size;
        }
      }

      .drawer-setting-container {
        margin-right: 28px;
        @include useTheme {
          color: getVar("iconColor");
        }
        .setting-button {
          @include useTheme {
            color: getVar("iconColor");
          }
          font-size: $icon-font-size;
          & :hover {
            @include useTheme {
              color: getVar("iconActiveColor");
            }
          }
        }
      }

      .toolBar-personal-info {
        display: flex;
        align-items: center;
        .toolBar-avatar-image-container {
          display: flex;
          align-items: center;
        }
      }
    }
  }
}
</style>